Date.prototype.Format = function (fmt) { // author: meizz
  let o = {
    "M+": this.getMonth() + 1, // 月份
    "d+": this.getDate(), // 日
    "H+": this.getHours(), // 小时
    "m+": this.getMinutes(), // 分
    "s+": this.getSeconds(), // 秒
    "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
    "S": this.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (let k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

function read_clipboard(for_img, callback) {
  navigator.permissions.query({
    name: "clipboard-read"
  }).then(result => {
    console.log("clipboard-read:", result.state);
    if (result.state != "granted" && result.state != "prompt") {
      callback(undefined, null);
      return;
    }
    if (for_img) {
      navigator.clipboard.read().then(data => {
        for (let item of data) {
          for (const type of item.types) {
            if (type.startsWith("image/")) {
              item.getType(type).then(blob => {
                callback(blob, "." + type.split("/")[1]);
              });
              return;
            }
          }
        }
        callback(null, null);
      }).catch(err => {
        console.log(err);
        callback(undefined, null);
      });
    } else {
      navigator.clipboard.readText().then(text => {
        callback(text);
      });
    }
  });
}

function copy_text(text, callback) {
  // Chrome 66+ / Edge 79 支持
  setTimeout(function () {
    navigator.clipboard.writeText(text).then(() => {
      callback(text);
    }).catch(err => {
      console.log(err);
      callback(null);
    });
  }, 200);
}

function get_cookie(key, callback) {
  let manifest = chrome.runtime.getManifest();
  chrome.cookies.get({
    url: manifest.host_permissions[0],
    name: key
  }, function (cookie) {
    callback(cookie ? cookie.value : null);
  });
}

function generate_url_thumb(url_img, width) {
  return `${url_img}@${Math.ceil(width)}w.webp`;
}

function parse_timestamp(timestamp) {
  let timestamp_today = new Date().setHours(0, 0, 0, 0);
  let day_diff = (timestamp_today - timestamp) / (24 * 60 * 60 * 1000.0);
  if (timestamp >= timestamp_today) {
    return "今天";
  } else if (day_diff < 1) {
    return "昨天";
  } else if (day_diff < 7) {
    return `${Math.ceil(day_diff)}天前`;
  } else if (day_diff < 13) {
    return `一周前`;
  } else {
    return new Date(timestamp).Format("M月d日");
  }
}